package demo.spring.framework.aop;

import java.lang.reflect.Method;

import javax.annotation.Nullable;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.AfterReturningAdvice;
import org.springframework.aop.MethodBeforeAdvice;
import org.springframework.stereotype.Component;

import demo.java.lang.annotation.DataSource;
import demo.spring.framework.jdbc.datasource.lookup.RoutingDataSourceDemo;

@Component
public class DataSourceExchange implements MethodBeforeAdvice, AfterReturningAdvice {

    private static Logger log = LoggerFactory.getLogger(DataSourceExchange.class);

    /**
     * 拦截目标方法，获取由@DataSource指定的数据源标识，设置到线程存储中以便切换数据源
     */
    @Override
    public void before(Method method, Object[] args, @Nullable Object target) throws Throwable {
        if (method.isAnnotationPresent(DataSource.class)) {
            DataSource dataSource = method.getAnnotation(DataSource.class);
            RoutingDataSourceDemo.setDataSource(dataSource.value());
            log.debug("数据源切换至：" + RoutingDataSourceDemo.getDatasource());
        }
    }

    @Override
    public void afterReturning(@Nullable Object returnValue, Method method, Object[] args, @Nullable Object target)
            throws Throwable {
        RoutingDataSourceDemo.clearDataSource();
        log.debug("数据源已移除！");
    }

}
